package com.dragon.www.smarthome.util;

import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;

import com.dragon.www.smarthome.activity.MainActivity;
import com.dragon.www.smarthome.database.DataHelper;
import com.dragon.www.smarthome.entity.Device;
import com.dragon.www.smarthome.entity.User;
import com.dragon.www.smarthome.net.AUDPPacket;
import com.dragon.www.smarthome.service.UdpService;

import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by daiye on 16/3/24.
 */
public class Utils {

    /**
     * uri转filepath许
     * @param context
     * @param uri
     * @return
     */
    public static String getFilePath(Context context, Uri uri) {
        if ("content".equalsIgnoreCase(uri.getScheme())) {
            String[] projection = {"_data"};
            Cursor cursor = null;
            try {
                cursor = context.getContentResolver().query(uri, projection, null, null, null);
                int column_index = cursor.getColumnIndexOrThrow("_data");
                if (cursor.moveToFirst()) {
                    return cursor.getString(column_index);
                }
            } catch (Exception e) {
            }
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }
        return null;
    }

    /**
     * 判断sdcard是否存在
     *
     * @return true存在可读写 false不存在不可读写
     */
    public static boolean sdacrdExist() {
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            // Log.d(TAG, "sdcard is exist,read and write ok");
            return true;
        }
        // Log.d(TAG, "sdcard is not exist or can not read/write");
        return false;
    }

    public static File getFoder(String path) {
        if (!sdacrdExist()) {
            return null;
        }
        File folder = new File(getFolderPath() + ("".equals(path) ? "" : "/" + path));
        if (!folder.exists()) {
            folder.mkdirs();
        }
        return folder;
    }

    public static String getFolderPath() {
        return Environment.getExternalStorageDirectory() + "/smarthome/";
    }

    public static String getRealPathFromURI(Context context, Uri contentUri) {
        String res = null;
        String[] proj = { MediaStore.Images.Media.DATA };
        Cursor cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
        if(cursor.moveToFirst()){
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            res = cursor.getString(column_index);
        }
        cursor.close();
        return res;
    }

    /**
     * 验证邮箱名是否有效
     * @param email
     * @return
     */
    public static boolean isEmail(String email) {
        String str = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";
        Pattern p = Pattern.compile(str);
        Matcher m = p.matcher(email);
        return m.matches();
    }

    /**
     * 验证用户是否已登录
     *
     * @author taoli
     * @since 2015-11-19 下午04:57:36
     */
    public static boolean isUserLogin() {
        boolean isLogin = false;
        User userInfo = Config.getUserInfo();
        if (userInfo.getUserName() != null && userInfo.getUserName().length() > 0) {
            isLogin = true;
        }
        return isLogin;
    }

    /**
     * 字符串转字节数组
     * @param ip
     * @return
     */
    public static byte[]  convertIpToBytes(String ip) {
        String[] ips = ip.split(":|\\.");
        if (ips == null || ips.length != 4)
            throw new RuntimeException("IP 格式出错"+ip);
        byte[] result = new byte[4];
        for (int i=0; i<result.length; i++) {
            result[i] = (byte) Integer.parseInt(ips[i]);
        }
        return result;
    }

    /**
     * 判断是否为合法IP
     * @return the ip
     */
    public static boolean isboolIp(String ipAddress)
    {
        String ip = "([1-9]|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3}";
        Pattern pattern = Pattern.compile(ip);
        Matcher matcher = pattern.matcher(ipAddress);
        return matcher.matches();
    }

    /**
     * 返回当前盒子的地址
     * @return
     */
    public static String getCurrentBoxSocketAddress(long roomId) {
        Device box = DataHelper.getInstance().getDevice((int) roomId, MainActivity.TYPE_CONTROLLER);
        if (box == null) return null;
        return box.getIp();
    }

    public static Device getCurrentBox(long roomId) {
        Device box = DataHelper.getInstance().getDevice((int) roomId, MainActivity.TYPE_CONTROLLER);
        return box;
    }

    /**
     *
     * @return
     */
    public static UdpService.UDPSocketConnectRunnable getCurrentBoxRunnable(long roomId) {
        return UdpService.allSocketsMap.get(getCurrentBoxSocketAddress(roomId));
    }

    /**
     *
     * @param roomId
     */
    public static void sendAction(long roomId, AUDPPacket packet) {
        //检查盒子
        Device box = getCurrentBox(roomId);
        if (null == getCurrentBox(roomId)) {
            Log.d("MainActivity", roomId+"盒子不存在与db中...");
            return;
        }
        //查询指令
        UdpService.UDPSocketConnectRunnable udpSocketRunnable =
                com.dragon.www.smarthome.util.Utils.getCurrentBoxRunnable(roomId);
        if (udpSocketRunnable == null) {
            Log.d("MainActivity", "不存在资源");
            return;
        }
        if (!udpSocketRunnable.getConnectStatus().equals(UdpService.UdpConnectStatus.Connected)) {
            Log.d("MainActivity", "房间"+roomId+"网络未连接");
            return;
        }

        //校验ip格式
        String ip = box.getIp();
        if (!isboolIp(ip)) {
            Log.d("MainActivity", "房间IP："+ip+"配置出错");
            return;
        }

        try {
            SocketAddress address = new InetSocketAddress(InetAddress.getByAddress(
                    box.getDeviceName(), convertIpToBytes(ip)), UdpService.SOCKET_PORT);
            packet.setSocketAddress(address);
            UdpService.handlerSendPacket(packet);
            Log.d("MainActivity", com.dragon.www.smarthome.net.Utils.byte2HexString(packet.getAction()));
        }catch (IOException e) {

        }
    }

        private static long lastClickTime;
        public synchronized static boolean isFastClick(long delay) {
            long time = System.currentTimeMillis();
            if ( time - lastClickTime < delay) {
                return true;
            }
            lastClickTime = time;
            return false;

    }

    public static void eee(String msg) {
        Log.e(getTag(), buildMessage(msg));
    }

    //获取调用者的类名
    private static String getTag() {
        StackTraceElement[] trace = new Throwable().fillInStackTrace()
                .getStackTrace();
        String callingClass = "";
        for (int i = 2; i < trace.length; i++) {
            Class<?> clazz = trace[i].getClass();
            if (!clazz.equals(Utils.class)) {
                callingClass = trace[i].getClassName();
                //callingClass = callingClass.substring(callingClass.lastIndexOf('.') + 1);
                break;
            }
        }
        return callingClass;
    }

    //获取线程，方法名
    private static String buildMessage(String msg) {
        StackTraceElement[] trace = new Throwable().fillInStackTrace()
                .getStackTrace();
        String caller = "";
        for (int i = 2; i < trace.length; i++) {
            Class<?> clazz = trace[i].getClass();
            if (!clazz.equals(Utils.class)) {
                caller = trace[i].getMethodName();
                break;
            }
        }
        return String.format(Locale.CHINA, "[%d] %s: %s", Thread.currentThread()
                .getId(), caller, msg);
    }
}
